package _14_网络编程._2_TCP编程.单线程;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class Server {

    public static void main(String[] args) {
        ServerSocket serverSocket;
        Socket clientSocket;

        try{
            serverSocket = new ServerSocket(56799);
            System.out.println("server is running ....." + "," + System.currentTimeMillis());

            while (true) {
                clientSocket = serverSocket.accept();
                System.out.println("connected from " + clientSocket.getRemoteSocketAddress() + "," + System.currentTimeMillis());

                try (InputStream inputStream = clientSocket.getInputStream()) {
                    try (OutputStream outputStream = clientSocket.getOutputStream()) {
                        handle(inputStream, outputStream);
                    }
                }

            }

        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void handle(InputStream inputStream, OutputStream outputStream) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,StandardCharsets.UTF_8));
//        String str = "";
        int i = 0;

        bufferedWriter.write("hello \n");
        bufferedWriter.flush();

        while(true){
            System.out.println("server :: start ========= " + i);
            String str = bufferedReader.readLine();
            if(str.equals("bye")){
                bufferedWriter.write("bye bye\n");
                bufferedWriter.flush();
                break;
            }
            bufferedWriter.write("Response : " + str + "\n");
            bufferedWriter.flush();
            System.out.println("server :: end ========= " + i);
            i++;
        }
    }
}
